"""
认证工具函数
"""
from datetime import datetime, timedelta
from typing import Optional
from jose import JWTError, jwt
from passlib.context import CryptContext
from config import settings

# 密码加密上下文
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")


def verify_password(plain_password: str, hashed_password: str) -> bool:
    """验证密码"""
    return pwd_context.verify(plain_password, hashed_password)


def get_password_hash(password: str) -> str:
    """生成密码哈希"""
    return pwd_context.hash(password)


def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str:
    """创建JWT token"""
    to_encode = data.copy()
    
    if expires_delta:
        expire = datetime.utcnow() + expires_delta
    else:
        expire = datetime.utcnow() + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
    
    to_encode.update({"exp": expire})
    encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
    
    return encoded_jwt


def verify_token(token: str) -> Optional[dict]:
    """验证JWT token"""
    try:
        payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
        print(f"[SUCCESS] Token verified successfully, user_id: {payload.get('sub')}")
        return payload
    except JWTError as e:
        print(f"[ERROR] Token verification failed: {str(e)}")
        print(f"   Token: {token[:30]}...")
        print(f"   SECRET_KEY: {settings.SECRET_KEY[:20]}...")
        return None
    except Exception as e:
        print(f"[ERROR] Unexpected error verifying token: {str(e)}")
        return None


def get_current_user_id(token: str) -> Optional[int]:
    """从token获取当前用户ID"""
    payload = verify_token(token)
    if payload:
        user_id_str = payload.get("sub")
        if user_id_str:
            try:
                return int(user_id_str)
            except (ValueError, TypeError):
                return None
    return None


def create_refresh_token(data: dict) -> str:
    """创建Refresh Token（用于Token续命）"""
    to_encode = data.copy()
    expire = datetime.utcnow() + timedelta(days=settings.REFRESH_TOKEN_EXPIRE_DAYS)
    to_encode.update({"exp": expire, "type": "refresh"})
    return jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)


def verify_refresh_token(token: str) -> Optional[dict]:
    """验证Refresh Token"""
    try:
        payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
        if payload.get("type") != "refresh":
            return None
        return payload
    except:
        return None

